package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.fragments.BaseFragment;
import com.hxkcloud.patient.fragments.StopDrugsRecordFragment;
import com.hxkcloud.patient.fragments.TakeDrugsRecordFragment;
import com.hxkcloud.patient.popwindow.MyPopuWindow;
import com.hxkcloud.patient.views.MainViewPager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-10-06.
 * Description:患者端用药记录列表
 */
public class TakeDrugsActivity extends BaseFragmentActivity implements View.OnClickListener {


    public MainViewPager viewPager;
    public List<BaseFragment> fragments = new ArrayList<BaseFragment>();
    private FragmentManager fragmentManager;

    private TakeDrugsRecordFragment takeDrugsRecordFragment;
    private StopDrugsRecordFragment stopDrugsRecordFragment;

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_add;
    private TextView tv_tableName;
    private TextView tv_takeDrugs,tv_stopDrugs;

    public String drugId = "";
    public String patientId = "";

    @Override
    protected void updateByHandler(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takedrugs);

        drugId = getIntent().getStringExtra("drugid");
        if (getIntent().hasExtra("patientid")) {
            patientId = getIntent().getStringExtra("patientid");
        } else {
            patientId = loginInfo.getPatientId();
        }
        initView();
        initListener();
    }


    protected void initView() {

        viewPager = (MainViewPager) findViewById(R.id.viewPager_drugrecord);

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        iv_add = (ImageView) findViewById(R.id.iv_title_func);
        tv_tableName = (TextView) findViewById(R.id.tv_tableName);
        tv_takeDrugs = (TextView) findViewById(R.id.tv_takeDrugs);
        tv_stopDrugs = (TextView) findViewById(R.id.tv_stopDrugs);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.takedrugrecord));
        iv_add.setVisibility(View.VISIBLE);
        iv_add.setImageResource(R.drawable.nav_add);
        iv_back.setOnClickListener(this);
        iv_add.setOnClickListener(this);

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
            iv_add.setVisibility(View.VISIBLE);
        } else {
            iv_add.setVisibility(View.INVISIBLE);
        }



        takeDrugsRecordFragment = new TakeDrugsRecordFragment();
        stopDrugsRecordFragment = new StopDrugsRecordFragment();

        fragments.add(takeDrugsRecordFragment);
        fragments.add(stopDrugsRecordFragment);

        fragmentManager = this.getSupportFragmentManager();
        viewPager.setSlipping(true);//设置ViewPager是否可以滑动
        viewPager.setOffscreenPageLimit(0);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setCurrentItem(0);
        tv_tableName.setText(getResources().getString(R.string.takedrugrecord));

    }

    protected void initListener() {

        tv_takeDrugs.setOnClickListener(this);
        tv_stopDrugs.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func:
                if(MyPopuWindow.isShowing())
                {
                    MyPopuWindow.dismiss();
                    return;
                }
                MyPopuWindow.drugAction(TakeDrugsActivity.this, R.id.iv_title_func, new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        switch (v.getId())
                        {
                            case R.id.tv_addDrugRecord:  //添加服药记录
                                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                                    DrugListActivity.jumpToDrugListActivity(TakeDrugsActivity.this,patientId,0);
                                } else {
                                    toastMsg("暂无药品可选，请先加入科室！");
                                }
                                MyPopuWindow.dismiss();
                                break;
                            case R.id.tv_addStopDrugRecord: // 添加停药记录

                                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                                    DrugListActivity.jumpToDrugListActivity(TakeDrugsActivity.this,patientId,1);
                                } else {
                                    toastMsg("暂无药品可选，请先加入科室！");
                                }
                                MyPopuWindow.dismiss();
                                break;
                        }
                    }
                });
                break;
            case R.id.tv_takeDrugs:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tv_stopDrugs:
                viewPager.setCurrentItem(1);
                break;
        }
    }



    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    tv_takeDrugs.setTextColor(getResources().getColor(R.color.light_blue));
                    tv_stopDrugs.setTextColor(getResources().getColor(R.color.grey_text1));
                    tv_tableName.setText(getResources().getString(R.string.takedrugrecord));
                    break;
                case 1:
                    tv_takeDrugs.setTextColor(getResources().getColor(R.color.grey_text1));
                    tv_stopDrugs.setTextColor(getResources().getColor(R.color.light_blue));
                    tv_tableName.setText(getResources().getString(R.string.stopdrug_record));
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

//        @Override
//        public void destroyItem(View container, int position, Object object) {
//            ((ViewPager) container).removeView(fragments.get(position).getView());
//        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            ((ViewPager) container).removeView(fragments.get(position).getView());
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = fragments.get(position);
            //fragment.setVisibleToUser(true);
            if (!fragment.isAdded()) { // 如果fragment还没有added
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(fragment, fragment.getClass().getSimpleName());
                ft.commit();
                /**
                 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
                 * 会在进程的主线程中,用异步的方式来执行。
                 * 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
                 * 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
                 */
                fragmentManager.executePendingTransactions();
            }

            if (fragment.getView().getParent() == null) {
                container.addView(fragment.getView()); // 为viewpager增加布局
            }
            return fragment.getView();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == DrugListActivity.requestCode && resultCode == RESULT_OK)
        {
            if(data != null)
            {
                int intentType = data.getIntExtra("intentType",0);
                if(intentType == 0 || intentType == 1)
                {
                    viewPager.setCurrentItem(intentType);
                }
            }
        }
    }
}
